package everest3.procesosBibliotecarios;
import everest3.*;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;
import java.util.EventObject;
import java.util.Vector;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.EventListenerList;
import javax.swing.plaf.basic.BasicComboBoxUI;
import javax.swing.table.TableCellEditor;

public class ComboBox extends JComboBox implements TableCellEditor, CaretListener {

   protected  int elementos=0;
    
  protected EventListenerList listenerList = new EventListenerList();

  protected ChangeEvent changeEvent = new ChangeEvent(this);

  private MyComboUI comboUi = new MyComboUI();
private int fila;
  private JTextField tf;
  public boolean seleccion=false;

  Object newValue;
  public ComboBox(Vector vector)
    {    
        super();
        elementos=vector.size();
        removeAllItems();
         setUI(comboUi);        
      
        if (vector.size()>0)
        {
            DecimalFormat df1 = new DecimalFormat("000");
            for(int i=0; i<vector.size(); i++)
            addItem(df1.format(vector.elementAt(i)));
        }         
       
         
        
        
        setEditable(true);
          tf = (JTextField) getEditor().getEditorComponent();
        tf.addCaretListener(this);
    

    tf.addKeyListener(new KeyAdapter() {
      public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == e.VK_ENTER) {
          Object value = comboUi.getList().getSelectedValue();
          tf.transferFocus();
          hidePopup();
          System.out.println("enter pressed, selected value, when enter pressed: " + value);
          seleccion=true;
          fireEditingStopped();
        }
      }
    });

    addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        // fireEditingStopped();
      }
    });
    }
    
    public ComboBox(Vector vector, int filaA)
    {    
        super();
        elementos=vector.size();
        removeAllItems();
         setUI(comboUi);
        
        if(fila==filaA)
        {
             if (vector.size()>0){
             DecimalFormat df1 = new DecimalFormat("000");
            for(int i=0; i<vector.size(); i++)
                addItem(df1.format(vector.elementAt(i)));
        }         
        }
         
        
        
        setEditable(true);
          tf = (JTextField) getEditor().getEditorComponent();
        tf.addCaretListener(this);
    

    tf.addKeyListener(new KeyAdapter() {
      public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == e.VK_ENTER) {
          Object value = comboUi.getList().getSelectedValue();
          tf.transferFocus();
          hidePopup();
          System.out.println("enter pressed, selected value, when enter pressed: " + value);
          seleccion=true;
          fireEditingStopped();
        }
      }
    });

    addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
        // fireEditingStopped();
      }
    });
    }
    /**
     * Este metodo recibe los elementos a insertar en el combo box que en este caso son numeros
     * y les aplica un formato de numero de tres digitos 000
     * @param vector vector que contiene la informacion a insertar en el combo box
     */
    public void cargarDatos(Vector vector){   
         
      
        elementos=vector.size();
        if (vector.size()>0){
             DecimalFormat df1 = new DecimalFormat("000");
            for(int i=0; i<vector.size(); i++)
                addItem(df1.format(vector.elementAt(i)));
        }         
    }

    public void filaAsociada(int fila)
    {
        this.fila=fila;
        
    }
  public int getNumeroElementos(){
      return elementos;
  }
  public void addCellEditorListener(CellEditorListener listener) {
    listenerList.add(CellEditorListener.class, listener);
  }

  public void removeCellEditorListener(CellEditorListener listener) {
    listenerList.remove(CellEditorListener.class, listener);
  }

  protected void fireEditingStopped() {
    System.out.println("fireEditingStopped called ");

    CellEditorListener listener;
    Object[] listeners = listenerList.getListenerList();
    for (int i = 0; i < listeners.length; i++) {
      if (listeners[i] == CellEditorListener.class) {
        listener = (CellEditorListener) listeners[i + 1];
        listener.editingStopped(changeEvent);
      }
    }
  }

  protected void fireEditingCanceled() {
    CellEditorListener listener;
    Object[] listeners = listenerList.getListenerList();
    for (int i = 0; i < listeners.length; i++) {
      //if (listeners == CellEditorListener.class) {
      if (listeners[i] == CellEditorListener.class) {
        listener = (CellEditorListener) listeners[i + 1];
        listener.editingCanceled(changeEvent);
      }
    }
  }

  public void cancelCellEditing() {
    System.out.println("cancelCellEditing called ");
    fireEditingCanceled();
  }

  public boolean stopCellEditing() {
    System.out.println("stopCellEditing called ");
    fireEditingStopped();
    return true;
  }

  public boolean isCellEditable(EventObject event) {
    return true;
  }

  public boolean shouldSelectCell(EventObject event) {
    return true;
  }

  public Object getCellEditorValue() {
    System.out.println("getCellEditorValue called returning vlaue: " + newValue);
   try{
       tf.setText(newValue.toString());
   }
   catch(java.lang.Exception e){
       javax.swing.JOptionPane.showMessageDialog(this,"el libro no existe o se encuentra prestado\n"+e);
   }
    seleccion=true;   
    return newValue;
    // return super.getSelectedItem();
  }

  public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
      int row, int column) {

    return this;
  }

  public void caretUpdate(CaretEvent e) {
    if (!isPopupVisible() && tf.isShowing() && tf.hasFocus())
      showPopup();

    JTextField tf = (JTextField) e.getSource();
    String text = tf.getText().toLowerCase();

    int index = -1;
    for (int i = 0; i < super.getItemCount(); i++) {
      String item = ((String) getItemAt(i)).toLowerCase();
      if (item.startsWith(text)) {
        index = i;
        break;
      }
    }
    if (index != -1)
      comboUi.getList().setSelectedIndex(index);
    else
      comboUi.getList().clearSelection();

    newValue = comboUi.getList().getSelectedValue();
    System.out.println("new value set to: " + newValue);
    seleccion=true;
  }    
    
}

class MyComboUI extends BasicComboBoxUI {

  public JList getList() {
    return listBox;
  }
}
